package cn.edu.scau.sec.rw.controllers;

import cn.edu.scau.sec.rw.model.disk_file.disk.Disk;
import cn.edu.scau.sec.rw.model.disk_file.file.ExeFile;
import cn.edu.scau.sec.rw.model.disk_file.file.FileCatalog;
import cn.edu.scau.sec.rw.model.disk_file.file.TextFile;
import cn.edu.scau.sec.rw.model.disk_file.file.VirtualFile;
import cn.edu.scau.sec.rw.model.disk_file.utils.File_DiskUtil;
import cn.edu.scau.sec.rw.model.pro_manage.Process;
import cn.edu.scau.sec.rw.model.pro_manage.pro_dispatch.Dispatch;
import cn.edu.scau.sec.rw.model.pro_manage.simulation.Interrupt;
import cn.edu.scau.sec.rw.model.pro_manage.threadExe.CPUThread;
import cn.edu.scau.sec.rw.model.pro_manage.threadExe.SysTimeThread;
import cn.edu.scau.sec.rw.view.CreateCatalogUI;
import cn.edu.scau.sec.rw.view.CreateFileUI;
import cn.edu.scau.sec.rw.view.GlobalMenu;
import com.sun.javafx.scene.control.skin.LabeledText;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;

import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

public class Disk_FileUIController implements Initializable {

    @FXML
    private AnchorPane Apane;

    @FXML
    private Button min;

    @FXML
    private Button close;

    @FXML
    private TreeView<VirtualFile> treeView;

    @FXML
    private GridPane gridPane;

    private Disk disk;
//    private Disk_FileUIController controller;
//
//    public Disk_FileUIController(){
//        controller = this;
//    }

    @FXML
    void close(MouseEvent event) {
        if(event.getButton().name().equals(MouseButton.PRIMARY.name()))
            CommonBridge.stage.close();
        CommonBridge.stage = null;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        disk = Disk.getDisk();
        for (int i = 0; i < disk.getFAT().length; i++) {
            System.out.print(disk.getFAT()[i] + " ");
        }
        initTreeView(disk);
        addRightMenu(treeView);
        initGridPane(gridPane);
        CommonBridge.gridPane = gridPane;
//        System.out.println("end");

    }

    private void addRightMenu(TreeView<VirtualFile> treeView) {
        treeView.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                if (event.getButton() == MouseButton.SECONDARY) {

                    Node node = event.getPickResult().getIntersectedNode();
                    if (node instanceof LabeledText){
                            GlobalMenu menu = GlobalMenu.getInstance(node);
                            initHandler(treeView,menu);
                            if(treeView.getSelectionModel().getSelectedItem().getValue() instanceof FileCatalog){

                                menu.getItems().get(0).setDisable(true);
                                menu.getItems().get(3).setDisable(true);

                                if (CommonBridge.pasteAllow == true){
                                    menu.getItems().get(4).setDisable(false);

                                }else {
                                    menu.getItems().get(4).setDisable(true);
                                }
                                menu.getItems().get(1).setDisable(false);
                                menu.getItems().get(2).setDisable(false);
                                if (treeView.getSelectionModel().getSelectedItem().getValue() == disk.getRoot()){
                                    menu.getItems().get(5).setDisable(true);
                                } else menu.getItems().get(5).setDisable(false);

                            }
                            else {
                                menu.getItems().get(1).setDisable(true);
                                menu.getItems().get(2).setDisable(true);

                                menu.getItems().get(0).setDisable(false);

                                if (CommonBridge.pasteAllow == true){
                                    menu.getItems().get(3).setDisable(true);

                                }else {
                                    menu.getItems().get(3).setDisable(false);
                                }
                                menu.getItems().get(4).setDisable(false);
                                menu.getItems().get(5).setDisable(false);
                            }
                            menu.show(node, javafx.geometry.Side.BOTTOM, 0, 0);
                    }
//                    String name = treeView.getSelectionModel().getSelectedItem().getValue();
//                    System.out.println("Node click: " + name);
                }
            }
        });
    }

    private void initHandler(TreeView<VirtualFile> treeView,GlobalMenu menu) {

        MenuItem open = menu.getItems().get(0);
        MenuItem createCatalog = menu.getItems().get(1);
        MenuItem createFile = menu.getItems().get(2);
        MenuItem copy = menu.getItems().get(3);
        MenuItem paste = menu.getItems().get(4);
        MenuItem delete = menu.getItems().get(5);

        TreeItem<VirtualFile> selectedItem = treeView.getSelectionModel().getSelectedItem();

        delete.setOnAction(event -> {

            System.out.println(selectedItem);
            TreeItem<VirtualFile> parent = selectedItem.getParent();
            ((FileCatalog)parent.getValue()).remove(selectedItem.getValue());
            File_DiskUtil.deleteVirtualFile(selectedItem.getValue());
            selectedItem.getParent().getChildren().remove(selectedItem);
            alterGridPane(gridPane);
        });

        open.setOnAction(event -> {
            //cpu（）
            Dispatch.initProcess((ExeFile)selectedItem.getValue());
        });

        createCatalog.setOnAction(event -> {
            new CreateCatalogUI(selectedItem);
            alterGridPane(gridPane);
        });

        createFile.setOnAction(event -> {
            CommonBridge.item = selectedItem;
            new CreateFileUI();
            alterGridPane(gridPane);
        });

        copy.setOnAction(event -> {

            CommonBridge.item_copy = treeView.getSelectionModel().getSelectedItem();
            CommonBridge.pasteAllow = true;
            alterGridPane(gridPane);
        });

        paste.setOnAction(event -> {

            boolean isDoubleName = false;

            TreeItem<VirtualFile> item = treeView.getSelectionModel().getSelectedItem();
            for (TreeItem<VirtualFile> child : item.getChildren()) {
                if (child.getValue().getName().equals(CommonBridge.item_copy.getValue().getName())){
                    isDoubleName = true;
                    break;
                }
            }

            ArrayList<String> statements = new ArrayList<>();
            String content = null;
            String name = null;
            TreeItem<VirtualFile> item1 = null;
            VirtualFile file = null;

            if (CommonBridge.item_copy.getValue() instanceof ExeFile){

                for (String s : ((ExeFile) CommonBridge.item_copy.getValue()).getStatements()) {
                    statements.add(s);
                }
            }else content = ((TextFile) CommonBridge.item_copy.getValue()).getContent();


            if (isDoubleName)
                if (CommonBridge.item_copy.getValue() instanceof TextFile){
                    name = CommonBridge.item_copy.getValue().getName() + "_cp";
                }else {
                    String[] subName = CommonBridge.item_copy.getValue().getName().split("\\.");
                    StringBuffer str = new StringBuffer();
                    str.append(subName[0]);
                    str.append("_cp.");
                    str.append(subName[1]);
                    name = str.toString();
                }
            else name = CommonBridge.item_copy.getValue().getName();

            if (CommonBridge.item_copy.getValue() instanceof ExeFile){
                file = new ExeFile(name,statements,statements.size());
                item1 = new TreeItem<>(file);
            }else {
                file = new TextFile(name, content, content.length()/3);
                item1 = new TreeItem<>(file);
            }

            item.getChildren().add(item1);
            ((FileCatalog) selectedItem.getValue()).add(file);
            File_DiskUtil.saveVirtualFile(item1.getValue());
            CommonBridge.item_copy =null;
            CommonBridge.pasteAllow = false;
            alterGridPane(gridPane);
        });
    }

    /**
     * 初始化显示磁盘块
     * @param gridPane
     */
    private void initGridPane(GridPane gridPane) {
        alterGridPane(gridPane);
    }

    private void alterGridPane(GridPane gridPane) {

        int[] FAT = disk.getFAT();
//        for (int i : FAT) {
//            System.out.print( i + " ");
//        }
        int index = 0;
        for (Node child : gridPane.getChildren()) {
//            System.out.println(child);
//            System.out.print(index+" ");
            if (FAT[index] != 0)
                child.setStyle("-fx-fill: crimson");
            else child.setStyle("-fx-fill: #E0FFFF");
            index ++;
        }
        System.out.println("end");
    }


    /**
     * 初始化treeView
     * @param disk
     */
    private void initTreeView(Disk disk) {

        TreeItem<VirtualFile> root = new TreeItem<>(disk.getRoot());
        System.out.println(root);
        treeView.setRoot(root);
//        System.out.println("root:" + disk.getRoot().getName());
        root.setExpanded(true);
//        treeView.setShowRoot(false);
        addChild(root, disk.getRoot());
    }



    private void addChild(TreeItem<VirtualFile> item, FileCatalog fileCatalog) {

        if (fileCatalog.getChild().size()!=0){
            for (VirtualFile file : fileCatalog.getChild()) {
                TreeItem<VirtualFile> treeItem = new TreeItem<>(file);
                item.getChildren().add(treeItem);
                if (file instanceof FileCatalog) addChild(treeItem, (FileCatalog) file);
            }
        }
    }

}
